<template>
  <view>
    <view class="goods-list">
      <view class="" v-if="goodsList.length===0" class="goods-no">
        暂无商品
      </view>
      <!-- 商品列表 -->
      <view v-for="item in goodsList" :key="item.goods_id" @click="gotoDetail(item)">
        <my-goods :goods="item"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 请求参数
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10
        },
        goodsList: [],
        total: 0, // 总数
        isloading: false,
        isfinish: false
      };
    },
    onLoad(options) {
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
    },
    methods: {
      // 获取商品列表
      async getGoodsList(cb) {
        this.isloading = true
        const {
          data
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        this.isloading = false
        cb && cb() // 加载完成触发回调
        // 请求失败
        if (data.meta.status !== 200) return uni.$showMsg()
        // 成功
        if (data.message.goods.length === 0) this.isfinish = true
        this.goodsList = [...this.goodsList, ...data.message.goods]
        this.total = data.message.total
      },
      // 上拉加载更多
      onReachBottom() {
        if (this.isloading) return
        if (this.isfinish) return uni.$showMsg('没有更多了')
        this.queryObj.pagenum++
        this.getGoodsList()
      },
      // 下拉刷新
      onPullDownRefresh() {
        this.queryObj.pagenum = 1
        this.total = 0
        this.isloading = false
        this.isfinish = false
        this.goodsList = []
        this.getGoodsList(() => uni.stopPullDownRefresh())
      },
      // 点击商品
      gotoDetail(goods) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      }
    }
  }
</script>

<style lang="scss">
  .goods-no {
    text-align: center;
    color: gray;
    padding: 10px;
  }
</style>
